package com.monkeyk.sos.web.controller.common;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.monkeyk.sos.domain.model.CooperDetails;
import com.monkeyk.sos.domain.shared.security.WdcyUserDetails;
import com.monkeyk.sos.service.CommonService;
import com.monkeyk.sos.service.CooperService;
import com.monkeyk.sos.util.WebUtils;
import com.monkeyk.sos.web.controller.BaseController;

/**
* @ClassName: CommonController 
* @Description: 公共控制器
* @author cygaod 
* @date 2015年12月10日 下午4:49:05 
* @version 1.0
 */
@Controller
@RequestMapping("/common")
public class CommonController extends BaseController {
	private static final Logger	Log	= Logger.getLogger(CommonController.class);

	@Autowired
	private CooperService		cooperService;
	
	@Autowired
	private CommonService		commonService;
	
	/**
	* @Title: loginPortal 
	* @Description: 跳转前端登录页面 
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
	@RequestMapping("/loginPortal")
    public String loginPortal() {
		return "../../portalLogin";
    }
	
	
	/**
	* @Title: moblieApply 
	* @Description: 移动应用申请 
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
    @RequestMapping("/mobileApply")
    public String moblieApply() {
    	Log.info("moblieApply ："+"moblie/mobileApply");
    	return "portal/mobile/apply";
    }
	
    /**
    * @Title: webApply 
    * @Description: 网站应用申请
    * @param @return    设定文件 
    * @return String    返回类型 
    * @throws
     */
	@RequestMapping("/webApply")
	public String webApply() {
		Log.info("webApply ：" + "web/webApply");
		return "portal/web/apply";
	}
	
	/**
	* @Title: CooperatorApply 
	* @Description: 合作者注册 
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
	@RequestMapping("/register")
	public String CooperatorApply() {
		return "portal/common/register";
	}
	
	
	/**
	* @Title: saveCooper 
	* @Description: 合作者注册保存 
	* @param @param cooper
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
	@RequestMapping(value="/saveCooper",method = RequestMethod.POST)
	public String saveCooper(CooperDetails cooper) {
		Log.info("保存合作者 : " + "common/saveCooper");
		cooper.setPassword(WebUtils.md5(cooper.getPassword()));
		cooperService.saveCooper(cooper);
		return "../../portalLogin";
	}
	
	/**
	* @Title: saveManager 
	* @Description: 管理员保存 
	* @param @param manager
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
	@RequestMapping(value="/saveManager",method = RequestMethod.POST)
	public String saveManager(CooperDetails manager) {
	    Log.info("保存管理员 : " + "common/saveManager");
	    manager.setPassword(WebUtils.md5(manager.getPassword()));
	    cooperService.saveCooper(manager);
	    return "redirect:"+"/syslogin.jsp";
	}
	/**
	 * @throws IOException 
	 * 
	*
	* @Title: checkCooper 
	* @Description: 校验合作者名称唯一性 
	* @param     设定文件 
	* @return void    返回类型 
	* @throws
	 */
	@RequestMapping("/checkCooperName")
	public void checkCooperName(String cooperName,HttpServletResponse response) throws IOException {
		response.reset();
		final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        final Object principal = authentication.getPrincipal();
        boolean status = cooperService.checkCooper(cooperName);
        if(principal instanceof String || principal instanceof org.springframework.security.core.userdetails.User){
    		response.getWriter().print(status);
        }else{
        	if(status){
        		response.getWriter().print(true);
            }else if (((WdcyUserDetails)principal).getUsername().equals(cooperName)) {
            	response.getWriter().print(true);
			}else {
				response.getWriter().print(false);
			} 
        }
	}

	
	
	/**
	* @Title: checkPhone 
	* @Description: 发送短信，保存验证码 
	* @param @param email
	* @param @param session
	* @param @param response    设定文件 
	* @return void    返回类型 
	* @throws
	 */
	@RequestMapping(value="/getMessCode",method=RequestMethod.POST)
	public void checkPhone( String phone,HttpSession session,HttpServletResponse response) {
	    Log.info("验证手机号 : " + "/getMessCode/"+phone);
	    Map<String, Object> map= new HashMap<String, Object>();
	    String status = commonService.getMessCodeStatus(phone);
	    if(status.equals("type1")){
	    	map.put("status", false);//手机号已注册
	    	map.put("failMess", "手机号已注册，请更换手机或者直接登录！");
	    }else if(status.equals("type2")){
	    	map.put("status", false);//短信验证达到最大上限
	    	map.put("failMess", "已达到当天最大手机验证码获取次数（10次），请次日再进行相关操作！");
	    }else {
	    	Map<String, String> result = WebUtils.sendMsg(phone);
		    String failMess = result.get("status");
		    if(failMess != ""){
		    	map.put("status", false);//短信发送失败
		    	map.put("failMess", failMess);
		    }else{
		    	map.put("status", true);//短信发送成功
		    	int codeId = commonService.saveMessCode(phone, null, result.get("code"));
		    	map.put("codeId", codeId);//验证码保存ID
			    Log.info("code" + result.get("code"));
		    };
		}
	    writeJSON(response, map);
	}
	
	/**
	* @Title: checkCode 
	* @Description: 校验验证码 
	* @param @param code
	* @param @param session
	* @param @param response    设定文件 
	* @return void    返回类型 
	* @throws
	 */
	@RequestMapping(value="/checkMessCode",method=RequestMethod.POST)
	public void checkMessCode(String code,String password,String phone,String codeId,HttpSession session,HttpServletResponse response) {
	    Log.info("验证验证码 : " + "/checkMessCode/"+code);
	    String status = commonService.checkMessCode(codeId, code, WebUtils.md5(password));
	    Map<String, Object> map= new HashMap<String, Object>();
		map.put("status", status);
		writeJSON(response, map);
	}
	
}
